package com.xiaoke.java1;

import java.lang.ref.WeakReference;

/**
 * @author yd
 * @version 1.0
 * @date 2022/3/10 20:44
 */
public class WeakReferenceTest { public static class User{
    public int id;
    public String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}


    public static void main(String[] args) {

        //构造弱引用
        WeakReference<User> userWeakRef = new WeakReference<User>(new User(1, "xiaoke"));
        //从软引用中重新获得强引用对象
        System.out.println(userWeakRef.get());

        System.gc();

        //不管当前内存空间足够与否，都会回收它的内存！
        System.out.println("After gc");
        //重新尝试从弱引用中获取对象
        System.out.println(userWeakRef.get());






    }
}
